﻿using CDV.IRMS.WebAPI.TaskExecution.Data;
using CDV.IRMS.WebAPI.TaskExecution.Utils;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace CDV.IRMS.WebAPI.TaskExecution.Interface.Impl
{
    /// <summary>
    /// IP矩阵控制实现类
    /// </summary>
    public class IPMatrixControlServiceImpl : IMatrixControlService
    {
        /// <summary>
        /// Log对象
        /// </summary>
        private readonly ILog _logger = ServiceInjector.ServiceProvider.GetService<ILog>();

        /// <summary>
        /// 矩阵控制接口API
        /// </summary>
        public RESTfulAPI RESTfulAPI { get; set; }

        /// <summary>
        /// 矩阵流切换
        /// </summary>
        /// <param name="srcNodeID">源流节点ID</param>
        /// <param name="destNodeID">目的流节点ID</param>
        /// <param name="switchID">矩阵ID</param>
        /// <returns>true：切换成功</returns>
        public (bool, string) Take(string srcNodeID, string destNodeID, long? switchID = null)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(RESTfulAPI.BaseURL);
                httpClient.Timeout = RESTfulAPI.TimeOut;

                var requestUri = string.Format(RESTfulAPI.APIMap["Take"], destNodeID, srcNodeID);
                var response = httpClient.GetAsync(requestUri);
                if (response.Result.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResult = response.Result.Content.ReadAsStringAsync().Result;

                    var result = JsonConvert.DeserializeAnonymousType(jsonResult, new { isOK = false, msg = "" });

                    _logger.Debug($"RequestUri: {requestUri}, Result: [IsOK={result.isOK}, Msg={result.msg}]");

                    return (result.isOK, result.msg);
                }

                return (false, $"矩阵流[源节点ID:{srcNodeID}--->目的节点ID:{destNodeID}]切换失败[StatusCode:{response.Result.StatusCode}]");
            }
        }

        /// <summary>
        /// 锁定矩阵目的流
        /// </summary>
        /// <param name="destNodeID">目的流节点ID</param>
        /// <param name="switchID">矩阵ID</param>
        /// <returns>true：锁定成功</returns>
        public (bool, string) Lock(string destNodeID, long? switchID = null)
        {
            return LockOrUnlock("Lock", destNodeID);
        }

        /// <summary>
        /// 解锁矩阵目的流
        /// </summary>
        /// <param name="destNodeID">目的流节点ID</param>
        /// <param name="switchID">矩阵ID</param>
        /// <returns>true：解锁成功</returns>
        public (bool, string) UnLock(string destNodeID, long? switchID = null)
        {
            return LockOrUnlock("Unlock", destNodeID);
        }

        /// <summary>
        /// 锁定/解锁矩阵目的流
        /// </summary>
        /// <param name="action">Lock or Unlock</param>
        /// <param name="destNodeID">目的流节点ID</param>
        /// <returns>true：锁定/解锁成功</returns>
        private (bool, string) LockOrUnlock(string action, string destNodeID)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(RESTfulAPI.BaseURL);
                httpClient.Timeout = RESTfulAPI.TimeOut;

                var requestUri = string.Format(RESTfulAPI.APIMap[action], destNodeID);
                var response = httpClient.GetAsync(requestUri);
                if (response.Result.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResult = response.Result.Content.ReadAsStringAsync().Result;

                    var result = JsonConvert.DeserializeAnonymousType(jsonResult, new { isOK = false, msg = "" });

                    _logger.Debug($"RequestUri: {requestUri}, Result: [IsOK={result.isOK}, Msg={result.msg}]");

                    return (result.isOK, result.msg);
                }

                return (false, $"[{action}]矩阵目的流[节点ID：{destNodeID}]失败[StatusCode:{response.Result.StatusCode}]");
            }
        }
    }
}
